import React, {
    useState,
    useEffect,
    useMemo,
    useCallback,
    useLayoutEffect
} from "react"
import { connect, useDispatch } from "react-redux"
import {
    LgSideBarA,
    LgTabs
} from "lancoo-web-ui"
import { HashRouter as Router, Route } from "react-router-dom"
import { registerMicroApps, start } from 'qiankun';
import { getQueryVariable, removeToken } from "../../util";
import axiosMethod from "../../util/axios";
import $ from "jquery";
import "./index.scss"
import QiankunPage from "./qiankunPage";
import IframePage from "./iframePage";
import Scrollbars from "react-custom-scrollbars";
import { message } from "antd";
import InfoCentralLog from "./infoCentralLog";
import BackupsHistory from "./drawer/backupsHistory";

const skinColors = {
    "1": "#083E79",
    "2": "#0290FD",
    "3": "#003CB2",
    "4": "#036638",
    "5": "#4C40AB",
    "6": "#A60808"
}

const pageParams = {
    "app-count-statistics": {
        type: "qiankun",
        sysId: "Y01",
        key: "app-count-statistics",
        url: "homepage/web/html/appManager/index.html#/app-count-statistics",
        params: ['baseUrl', 'token', 'iframe']
    },
    "app-usage-statistics": {
        type: "qiankun",
        sysId: "Y01",
        key: "app-usage-statistics",
        url: "homepage/web/html/appManager/index.html#/app-usage-statistics",
        params: ['baseUrl', 'token', 'iframe']
    },
    "log-absence": {
        type: "iframe",
        sysId: "Y01",
        key: "log-absence",
        url: "web/serv/index.html?lg_tk=[token]&lg_ic=[identityCode]&iframe=true&logType=leave#/logPage"
    },
    "log-oaserver": {
        type: "iframe",
        key: "log-oaserver",
        sysId: "Y01",
        url: "web/serv/index.html?lg_tk=[token]&lg_ic=[identityCode]&iframe=true#/logPage",
        // params: ['baseUrl', 'token'],
    },

    "log-infocentral-system": {
        type: "self",
        sysId: "491",
        key: "log-infocentral-system",
        url: "/backups/index.html#/backups-reduction",
        params: ['baseUrl', 'token', 'iframe']
    },
}

function SideBar(props) {
    let {
        userInfo,
        currentIdentity,
        identityList,
        sysAddrInfo,
        sysInfo,
        skinInfo
    } = props
    const dispatch = useDispatch()
    const [dark, setDark] = useState(false)
    const [open, setOpen] = useState(true)
    const [menuList, setMenuList] = useState([])
    const [historyList, setHistoryList] = useState([])
    const [historyIndex, setHistoryIndex] = useState(0)


    const darkChange = () => {
        if (dark) {
            document.body.classList.add("light-dark");
        } else {
            document.body.classList.remove("light-dark");
        }
        setDark(!dark)
    }
    const openChange = () => {
        setOpen(!open)
    }
    const update = (data) => {
        let sign = false;
        data.forEach((item) => {
            Array.isArray(item.sublist) &&
                item.sublist.forEach((child) => {
                    if (child.info.key === "server-management" && child.selected) {
                        sign = true;
                    }
                })
        })
        if (sign) {
            return;
        }
        setMenuList(data)
    }

    const openWebPage = useCallback((data) => {
        let url = data.url.replace("[token]", sessionStorage.getItem("token")).replace("[identityCode]", currentIdentity.identityCode);
        window.open(sysAddrInfo[data.sysId]?.webSvrAddr + url);
    }, [sysAddrInfo, currentIdentity]);

    const updateMenuSelected = (list, router, callback) => {
        list.forEach((item) => {
            if (item?.info?.router === router) {
                item.selected = true
                if (item.color === "auto") {
                    document.body.classList.add("nav-auto");
                } else {
                    document.body.classList.remove("nav-auto");
                }
            } else {
                item.selected = false
            }
            Array.isArray(item.sublist) &&
                item.sublist.forEach((child) => {
                    if (child?.info?.router === router) {
                        child.selected = true
                        if (child.color === "auto") {
                            document.body.classList.add("nav-auto");
                        } else {
                            document.body.classList.remove("nav-auto");
                        }
                    } else {
                        child.selected = false
                    }
                })
        })
        callback(list)
    }
    const selectedItem = useCallback((data) => {
        console.log("选中的item", data)
        if (data.info.key === "server-management") {
            openWebPage(pageParams[data.info?.key]);
            return;
        }
        if (data.color === "auto") {
            document.body.classList.add("nav-auto");
        } else {
            document.body.classList.remove("nav-auto");
        }
        window.location.hash = `#/${data.info.router}`


        let list = JSON.parse(JSON.stringify(historyList))
        let historyOne = {
            key: data.info.key,
            label: data.text,
            info: data.info,
        }
        let exist = false
        list.forEach((item, index) => {
            if (item.key === data.info.key) {
                exist = index
            }
        })
        if (typeof exist === "number") {
            setHistoryIndex(exist)
        } else {   //之前没点击过，就把点击的导航添加到历史记录里
            list.push(historyOne)
            setHistoryIndex(list.length - 1)
        }
        if (list.length === 1) {
            list[0].closable = false
        } else {
            list.forEach(item => item.closable = true)
        }
        if (pageParams[data.info?.key]?.type === "open") {
            openWebPage(pageParams[data.info?.key]);
        }
        setHistoryList(list)
    }, [historyList, openWebPage])

    const historyClick = useCallback((index) => {
        let one = historyList[index]
        console.log(one)
        // let menu = JSON.parse(JSON.stringify(menuList))
        let menu = menuList
        updateMenuSelected(menu, one.info.router, function (arr) {
            setMenuList(arr)
        })
        setHistoryIndex(index)
        if (pageParams[one.info?.key]?.type === "open") {
            openWebPage(pageParams[one.info?.key]);
        }
        window.location.hash = `#/${one.info.router}`
    }, [menuList, historyList])

    const historyClose = useCallback((index) => {
        let list = JSON.parse(JSON.stringify(historyList))
        // let menu = JSON.parse(JSON.stringify(menuList))
        let menu = menuList;
        list.splice(index, 1)
        let one = list[index > list.length - 1 ? index - 1 : index]
        updateMenuSelected(menu, one.info.router, function (arr) {
            setMenuList(arr)
        })
        if (list.length === 1) {
            list[0].closable = false
        } else {
            list.forEach(item => item.closable = true)
        }
        setHistoryList(list)
        setHistoryIndex(index > list.length - 1 ? index - 1 : index)
        window.location.hash = `#/${one.info.router}`
    }, [menuList, historyList])

    // 查询出identityList里能进入moduleIds模块里的identityCode
    const checkModulesIdentity = (moduleIDs) => {
        return new Promise(resolve => {
            let obj = {
                ModuleID: moduleIDs,
                UserID: userInfo.userId
            };
            if (!moduleIDs) {
                resolve("");
                return;
            }
            axiosMethod({
                type: "post",
                url:
                    sessionStorage.getItem("baseUrl") +
                    "/UserMgr/PowerMgr/ValidateIdentity",
                body: obj,
                callback: (res, result) => {
                    if (result.ErrCode != 0) {
                        resolve("");
                        return;
                    }
                    resolve(Boolean(result.Data));
                }
            });
        });
    };
    const checkRole = (arr) => {
        return new Promise((resolve, reject) => {
            let count = 0;
            arr.forEach(async (item) => {
                item.role = await checkModulesIdentity(item.moduleId);
                console.log(item.role)
                count++;
                if (count === arr.length) {
                    resolve(arr);
                }
            })
        })
    }
    //通过hash，判断定位到哪个界面
    useLayoutEffect(() => {
        //获取分类列表
        let hash = window.location.hash.replace("#/", "")
        console.log(hash)
        let navList = [
            {
                text: "消息中心",
                open: true,
                moduleId: "Y01002",
                info: {
                    key: "log-infocentral-system",
                    router: "log-infocentral-system"
                },
                icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
                        <g id="社团组织管理" transform="translate(-94.993 -98.48)">
                            <path id="路径_285" data-name="路径 285" d="M104.216,99.743l6.205,3.189-6.205,3.189-6.205-3.189,6.205-3.189m0-1.263a.8.8,0,0,0-.42.119l-7.2,3.7a.74.74,0,0,0,0,1.268l7.2,3.7a.8.8,0,0,0,.839,0l7.2-3.7a.74.74,0,0,0,0-1.268l-7.2-3.7A.8.8,0,0,0,104.216,98.48Z" transform="translate(-1.224 0)" fill="#0290fd" />
                            <path id="路径_286" data-name="路径 286" d="M102.985,509.522a1.4,1.4,0,0,1-.708-.191l-6.954-3.565a.6.6,0,0,1-.26-.813.62.62,0,0,1,.828-.255l6.994,3.586.021.013a.152.152,0,0,0,.159,0l.021-.013.022-.011,6.986-3.6a.62.62,0,0,1,.829.253.6.6,0,0,1-.258.813l-6.967,3.589A1.4,1.4,0,0,1,102.985,509.522Z" transform="translate(0 -398.629)" fill="#0290fd" />
                            <path id="路径_287" data-name="路径 287" d="M102.985,703.912a1.4,1.4,0,0,1-.708-.191l-6.954-3.565a.6.6,0,0,1-.26-.813.62.62,0,0,1,.828-.255l6.994,3.586.021.013a.152.152,0,0,0,.159,0l.021-.013.022-.011,6.986-3.6a.62.62,0,0,1,.829.253.6.6,0,0,1-.258.813l-6.967,3.59A1.4,1.4,0,0,1,102.985,703.912Z" transform="translate(0 -589.432)" fill="#0290fd" />
                        </g>
                    </svg>
                )
            },
            {
                text: "一网通办",
                open: true,
                moduleId: "Y01002",
                info: {
                    key: "log-oaserver",
                    router: "log-oaserver"
                },
                icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
                        <g id="社团组织管理" transform="translate(-94.993 -98.48)">
                            <path id="路径_285" data-name="路径 285" d="M104.216,99.743l6.205,3.189-6.205,3.189-6.205-3.189,6.205-3.189m0-1.263a.8.8,0,0,0-.42.119l-7.2,3.7a.74.74,0,0,0,0,1.268l7.2,3.7a.8.8,0,0,0,.839,0l7.2-3.7a.74.74,0,0,0,0-1.268l-7.2-3.7A.8.8,0,0,0,104.216,98.48Z" transform="translate(-1.224 0)" fill="#0290fd" />
                            <path id="路径_286" data-name="路径 286" d="M102.985,509.522a1.4,1.4,0,0,1-.708-.191l-6.954-3.565a.6.6,0,0,1-.26-.813.62.62,0,0,1,.828-.255l6.994,3.586.021.013a.152.152,0,0,0,.159,0l.021-.013.022-.011,6.986-3.6a.62.62,0,0,1,.829.253.6.6,0,0,1-.258.813l-6.967,3.589A1.4,1.4,0,0,1,102.985,509.522Z" transform="translate(0 -398.629)" fill="#0290fd" />
                            <path id="路径_287" data-name="路径 287" d="M102.985,703.912a1.4,1.4,0,0,1-.708-.191l-6.954-3.565a.6.6,0,0,1-.26-.813.62.62,0,0,1,.828-.255l6.994,3.586.021.013a.152.152,0,0,0,.159,0l.021-.013.022-.011,6.986-3.6a.62.62,0,0,1,.829.253.6.6,0,0,1-.258.813l-6.967,3.59A1.4,1.4,0,0,1,102.985,703.912Z" transform="translate(0 -589.432)" fill="#0290fd" />
                        </g>
                    </svg>
                )
            },
            {
                text: "请假",
                open: true,
                moduleId: "Y01002",
                info: {
                    key: "log-absence",
                    router: "log-absence"
                },
                icon: (
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
                        <g id="社团组织管理" transform="translate(-94.993 -98.48)">
                            <path id="路径_285" data-name="路径 285" d="M104.216,99.743l6.205,3.189-6.205,3.189-6.205-3.189,6.205-3.189m0-1.263a.8.8,0,0,0-.42.119l-7.2,3.7a.74.74,0,0,0,0,1.268l7.2,3.7a.8.8,0,0,0,.839,0l7.2-3.7a.74.74,0,0,0,0-1.268l-7.2-3.7A.8.8,0,0,0,104.216,98.48Z" transform="translate(-1.224 0)" fill="#0290fd" />
                            <path id="路径_286" data-name="路径 286" d="M102.985,509.522a1.4,1.4,0,0,1-.708-.191l-6.954-3.565a.6.6,0,0,1-.26-.813.62.62,0,0,1,.828-.255l6.994,3.586.021.013a.152.152,0,0,0,.159,0l.021-.013.022-.011,6.986-3.6a.62.62,0,0,1,.829.253.6.6,0,0,1-.258.813l-6.967,3.589A1.4,1.4,0,0,1,102.985,509.522Z" transform="translate(0 -398.629)" fill="#0290fd" />
                            <path id="路径_287" data-name="路径 287" d="M102.985,703.912a1.4,1.4,0,0,1-.708-.191l-6.954-3.565a.6.6,0,0,1-.26-.813.62.62,0,0,1,.828-.255l6.994,3.586.021.013a.152.152,0,0,0,.159,0l.021-.013.022-.011,6.986-3.6a.62.62,0,0,1,.829.253.6.6,0,0,1-.258.813l-6.967,3.59A1.4,1.4,0,0,1,102.985,703.912Z" transform="translate(0 -589.432)" fill="#0290fd" />
                        </g>
                    </svg>
                )
            },
        ]
        navList = checkRole(navList);
        navList.then((arr) => {
            console.log(arr)
            arr = arr.filter(item => item.role);
            console.log(arr)
            if (!arr.length) {
                message.warn("当前用户无权限访问，请重新登录");
                sessionStorage.removeItem("token");
                localStorage.removeItem("token");
            }
            let one = arr[0];
            console.log(one)
            let historyList = [{
                key: one?.info?.key,
                label: one?.text,
                info: {
                    key: one?.info?.key,
                    router: one?.info?.key
                },
            }]
            arr = arr.filter(item => !item.sysId || sysAddrInfo[item.sysId]);  //检查一级目录是否部署
            console.log(arr)
            arr = arr.map((item) => {  //检查子目录是否部署
                let obj = { ...item };
                if (Array.isArray(item.sublist)) {
                    obj.sublist = [];
                    item.sublist.forEach((child) => {
                        console.log(pageParams[child.info?.key])
                        console.log(sysAddrInfo)
                        if (pageParams[child.info?.key].sysId && sysAddrInfo[pageParams[child.info?.key].sysId]) {
                            obj.sublist.push(child);
                        }
                    })
                }
                return obj;
            })
            console.log(arr)
            arr = arr.filter(item => !item.sublist || item.sublist.length);
            console.log(arr)
            //如果是不存在的hash，则默认展示应用桌面界面
            let hashList = [];
            arr.forEach((item) => {
                if (item.sublist) {
                    item.sublist.forEach((child) => {
                        hashList.push(child.info?.key);
                    })
                } else {
                    hashList.push(item.info?.key);
                }
            })
            console.log(arr)
            if (!hash || hash == "undefined" || !hashList.filter(item => hash.indexOf(item) > -1).length) {
                hash = historyList[0].key
                window.location.hash = `#/${historyList[0].key}`
            }
            hash &&
                arr.forEach((item) => {
                    // if (item.info.router === hash) {
                    if (hash.indexOf(item.info.router) > -1) {
                        historyList = [{
                            key: item.info.key,
                            label: item.text,
                            info: item.info,
                        }]
                        item.selected = true
                        item.color = "#fff";
                        if (item.color === "auto") {
                            document.body.classList.add("nav-auto");
                        } else {
                            document.body.classList.remove("nav-auto");
                        }
                    } else {
                        item.selected = false
                    }
                    Array.isArray(item.sublist) &&
                        item.sublist.forEach((child) => {
                            // if (child.info.router === hash) {
                            if (hash.indexOf(child.info.router) > -1) {
                                historyList = [{
                                    key: child.info.key,
                                    label: child.text,
                                    info: child.info,
                                }]
                                child.selected = true
                                if (child.color === "auto") {
                                    document.body.classList.add("nav-auto");
                                } else {
                                    document.body.classList.remove("nav-auto");
                                }
                            } else {
                                child.selected = false
                            }
                        })
                })
            if (historyList.length === 1) {
                historyList[0].closable = false
            } else {
                historyList.forEach(item => item.closable = true)
            }
            console.log(arr)
            setHistoryList(historyList)
            update(arr)
        })
        return;
    }, [skinInfo.userSkin, sysAddrInfo])

    useEffect(() => {
        let arr = [];
        console.log(menuList.length)
        console.log(menuList)
        if (!menuList.length) {
            return;
        }
        menuList.forEach((item) => {
            if (item.sublist) {
                item.sublist.forEach((child) => {
                    if (pageParams[child.info?.key].type === "qiankun") {
                        arr.push(pageParams[child.info?.key]);
                    }
                })
            } else {
                if (pageParams[item.info?.key].type === "qiankun") {
                    arr.push(pageParams[item.info?.key]);
                }
            }
        })
        const getActiveRule = (hash) => (location) => location.hash.startsWith(hash);
        let apps = arr.map((item) => {
            let base = item.sysId === "000" ? sysInfo.baseUrl : sysAddrInfo[item.sysId].webSvrAddr;
            let token = sessionStorage.getItem("token");
            let url = item.url.replace("[token]", token).replace("[identityCode]", currentIdentity.identityCode);
            let params = {};
            item.params.forEach((child) => {
                if (child === "basename") {
                    params[child] = item.baseName;
                }
                if (child === "baseUrl") {
                    params[child] = base;
                }
                if (child === "token") {
                    params[child] = token;
                }
                if (child === "skin") {
                    params[child] = `s${skinInfo.userSkin}`;
                }
                if (child === "drawerContainer") {
                    params[child] = $(".app-sidebar")[0];
                }
                if (child === "iframe") {
                    params[child] = "true";
                }
                if (child === "page") {
                    params[child] = item.page;
                }
            })
            console.log(item.key, base + url, params)
            console.log(params)
            return {
                name: item.key,
                entry: base + url,
                container: "#platform-qiankun-container",
                // container: `#${item.key.replace("-", "")}`,
                activeRule: getActiveRule(`#/${item.key}`),
                props: params
            }
        })
        registerMicroApps(apps, {
            beforeLoad: (app) => console.log('before load', app.name),
            beforeMount: [(app) => console.log('before mount', app.name)],
        });
        start();

    }, [menuList, sysInfo, skinInfo, sysAddrInfo, currentIdentity]);

    return (
        <div className="app-sidebar">
            <LgSideBarA
                datalist={menuList}
                dark={dark}
                open={open}
                darkChange={darkChange}
                openChange={openChange}
                update={update}
                selectedItem={selectedItem}
            >
                <div className="app-side-bar-body">
                    <LgTabs
                        data={historyList}
                        position='top'
                        closable={true}
                        type='card'
                        defaultTabIndex={historyIndex}
                        contentIsShow={false}
                        onTabClick={historyClick}
                        onCloseClick={historyClose}
                    ></LgTabs>
                    <Scrollbars style={{ height: "calc(100vh - 114px)" }}>
                        {
                            pageParams[window.location.hash.replace("#/", "")]?.type === "iframe" ?
                                <IframePage data={pageParams[window.location.hash.replace("#/", "")]} /> :
                                pageParams[window.location.hash.replace("#/", "")]?.type === "qiankun" ?
                                    <div id="platform-qiankun-container"></div> :
                                    pageParams[window.location.hash.replace("#/", "")]?.type === "self" ?
                                        pageParams[window.location.hash.replace("#/", "")]?.key === "log-infocentral-system" ?
                                            <InfoCentralLog />
                                            :
                                            <InfoCentralLog /> :
                                        <InfoCentralLog />
                        }
                    </Scrollbars>
                    <BackupsHistory />
                </div>
            </LgSideBarA>
        </div>
    )
}

const mapProps = (state) => {
    return {
        userInfo: state.userInfo,
        currentIdentity: state.currentIdentity,
        identityList: state.identityList,
        sysInfo: state.sysInfo,
        sysAddrInfo: state.sysAddrInfo,
        skinInfo: state.skinInfo
    }
}
export default connect(mapProps)(SideBar)